package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.WebUserTokenDao;
import com.baitengsoft.patentapimonitor.api.entity.WebUserTokenEntity;
import com.baitengsoft.patentapimonitor.api.oauth2.TokenGenerator;
import com.baitengsoft.patentapimonitor.api.service.WebUserTokenService;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service("sysUserTokenService")
public class WebUserTokenServiceImpl implements WebUserTokenService {
    @Autowired
    private WebUserTokenDao webUserTokenDao;
    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    public WebUserTokenEntity queryByUserId(Long userId) {
        return webUserTokenDao.queryByUserId(userId);
    }

    @Override
    public void save(WebUserTokenEntity token) {
        webUserTokenDao.save(token);
    }

    @Override
    public void update(WebUserTokenEntity token) {
        webUserTokenDao.update(token);
    }

    @Override
    public Res createToken(long userId) {
        //生成一个token
        String token = TokenGenerator.WebgenerateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        WebUserTokenEntity tokenEntity = queryByUserId(userId);
        if (tokenEntity == null) {
            tokenEntity = new WebUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //保存token
            save(tokenEntity);
        } else {
            // tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //更新token
            update(tokenEntity);
        }

        Res r = Res.ok().put("token", tokenEntity.getToken()).put("expire", EXPIRE);

        return r;
    }

    @Override
    public void logout(long userId) {
        //生成一个token
        String token = TokenGenerator.WebgenerateValue();

        //修改token
        WebUserTokenEntity tokenEntity = new WebUserTokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        update(tokenEntity);
    }
}
